package com.binest.investorInclusion.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.*;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;


import com.binest.common.constant.HttpStatus;
import com.binest.common.core.page.TableDataInfo;
import com.binest.common.utils.DateUtils;
import com.binest.draftBox.mapper.DraftBoxMapper;
import com.binest.inclusionExamine.mapper.InclusionExamineMapper;
import com.binest.inclusionExamine.service.IInclusionExamineService;
import com.binest.investDetails.domain.InvestDetails;
import com.binest.investDetails.mapper.InvestDetailsMapper;
import com.binest.investDetails.service.IInvestDetailsService;
import com.binest.investorInclusion.domain.InvestmentSurvey;
import com.binest.investorInclusion.domain.InvestorInclusion;
import com.binest.investorInclusion.domain.JointInvestment;
import com.binest.investorInclusion.mapper.InvestorInclusionMapper;
import com.binest.investorInclusion.service.IInvestorInclusionService;
import com.binest.investorInclusionMain.mapper.InvestorInclusionMainMapper;
import com.binest.keyEvent.domain.KeyEvent;
import com.binest.keyEvent.mapper.KeyEventMapper;
import com.binest.keyEvent.service.IKeyEventService;
import com.binest.projectInclusion.domain.ProjectInclusion;
import com.binest.socialMediaConnection.domain.SocialMediaConnection;
import com.binest.socialMediaConnection.mapper.SocialMediaConnectionMapper;
import com.binest.socialMediaConnection.service.ISocialMediaConnectionService;
import com.binest.workExperience.domain.WorkExperience;
import com.binest.workExperience.service.IWorkExperienceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 投资机构收录Service业务层处理
 *
 * @author wwd
 * @date 2024-01-23
 */
@Service
public class InvestorInclusionServiceImpl implements IInvestorInclusionService
{

    @Autowired
    private InvestorInclusionMapper investorInclusionMapper;


    @Autowired
    private DraftBoxMapper draftBoxMapper;

    @Autowired
    private InclusionExamineMapper inclusionExamineMapper;



    @Autowired
    private InvestDetailsMapper investDetailsMapper;

    @Autowired
    private SocialMediaConnectionMapper socialMediaConnectionMapper;

    @Autowired
    private KeyEventMapper keyEventMapper;

    @Autowired
    private InvestorInclusionMainMapper investorInclusionMainMapper;
    @Autowired
    private ElasticsearchClient client;
    @Autowired
    private IInclusionExamineService inclusionExamineService;
    @Autowired
    private ISocialMediaConnectionService socialMediaConnectionService;

    @Autowired
    private IKeyEventService keyEventService;
    @Autowired
    private IInvestDetailsService investDetailsService;
    @Autowired
    private IWorkExperienceService workExperienceService;
    /**
     * 查询投资机构收录
     *
     * @param id 投资机构收录主键
     * @return 投资机构收录
     */
    @Override
    public InvestorInclusion selectInvestorInclusionById(String id)
    {
        InvestorInclusion  res=investorInclusionMapper.selectInvestorInclusionById(id);
        List<SocialMediaConnection> smcList=socialMediaConnectionService.selectSocialMediaConnectionByInId(id);
        if(smcList!=null)
        {
            res.setSmcList(smcList);
        }

        //关键事件
        List<KeyEvent> eventList =keyEventService.selectKeyEventListByInId(id);
        if(eventList!=null)
        {
            res.setEventList(eventList);
        }
        //工作经历
        List<WorkExperience> workExperienceList =workExperienceService.selectWorkExperienceByInId(id);
        if(workExperienceList!=null)
        {
            res.setWorkExperienceList(workExperienceList);
        }
        // 投资详情
        List<InvestDetails> investDetailsList=investDetailsService.selectInvestDetailsListByInId(id);
        if(investDetailsList!=null)
        {
            res.setInvestDetailsList(investDetailsList);
        }
        return res;
    }

    @Override
    public InvestorInclusion selectEsInvestorInclusionById(String id) throws Exception {
        InvestorInclusion res = new InvestorInclusion();
        try {
            // 执行查询
            SearchResponse<InvestorInclusion> searchResponse = client.search(srBuilder -> srBuilder
                            .index("investor_inclusion")
                            // 多个id查询
                            .query(queryBuilder -> queryBuilder
                                    .ids(idsQueryBuilder -> idsQueryBuilder
                                            .values(id))
                            )
                    , InvestorInclusion.class);

            //解析查询结果
            List<Hit<InvestorInclusion>> hitList = searchResponse.hits().hits();
            res = hitList.get(0).source();

        } catch (IOException e) {
            throw new Exception("查询ES数据失败");

        }


        return res;
    }

    @Override
    public List<JointInvestment> selectJointInvestmentList(String id, String lang) throws Exception {

        List<JointInvestment>   resList= selectListCount(id, lang);
        List<JointInvestment> result = resList.stream()
                // 表示id为key， 接着如果有重复的，那么从对象o1与o2中筛选出一个，这里选择o1，
                // 并把id重复，需要将nums和sums与o1进行合并的o2, 赋值给o1，最后返回o1
                .collect(Collectors.toMap(JointInvestment::getId, a -> a, (o1,o2)-> {
                    o1.setCount(o1.getCount() + o2.getCount());
                    return o1;
                })).values().stream().collect(Collectors.toList());
        Collections.sort(result, Comparator.comparingInt(JointInvestment::getCount).reversed());
        if(result.size()>10){
            result= result.subList(0, Math.min(result.size(), 10));
        }
        return result ;
    }



    public List<JointInvestment> selectListCount(String id,String lang) throws Exception {

        List<JointInvestment>  resList=new ArrayList<>();
        //通过id获取投资详情
        InvestorInclusion   investorInclusion = selectEsInvestorInclusionById(id);
        //获取其中投资详情
        List<InvestDetails>  investDetailsList= investorInclusion.getInvestDetailsList();
        if(investDetailsList!=null){
            List<InvestDetails>  newInvestDetailsList= new ArrayList<>();
            //根据项目名称去重
            newInvestDetailsList = investDetailsList.stream()
                    .distinct()
                    .collect(Collectors.toList());
            for(int x=0;x<newInvestDetailsList.size();x++ ){
                String  projectName=newInvestDetailsList.get(x).getProjectName();
                //查询项目名在原本投资机构详情中出现几次
                Map<String, Long> countByPropertyA = investDetailsList.stream()
                        .collect(Collectors.groupingBy(InvestDetails::getProjectName, Collectors.counting()));
                int projectNameCount = Math.toIntExact(countByPropertyA.get(projectName));
                List<Query> querie = new ArrayList<>();
                List<Query> queries = new ArrayList<>();
                //最新 最热
                String type = "";
                //最新
                type = "createTime.keyword";
                // 升序降序
                String esSort = "";
                //最新
                esSort = "Desc";
                //判断中英文  0英文  1中文
                Query byLang = TermQuery.of(a -> a
                        .field("lang")
                        .value(lang)
                )._toQuery();

                querie.add(byLang);
                //投资详情中项目名称
                Query projectNames = TermQuery.of(a -> a
                        .field("investDetailsList.projectName")
                        .value(projectName)
                )._toQuery();
                querie.add(projectNames);

                Query names = TermQuery.of(a -> a
                        .field("name")
                        .value(investorInclusion.getName())
                )._toQuery();
                queries.add(names);
                try {
                    // 从es中根据条件查询结果.
                    String finalType = type;
                    String finalEsSort = esSort;
                    SearchResponse<InvestorInclusion> searchResponse = client.search(s -> s
                                    .index("investor_inclusion")
                                    .query(q -> q
                                            .bool(t -> t
                                                    .must(querie)
                                                    .mustNot(queries)
                                            ))
                            , InvestorInclusion.class);
                    List<Hit<InvestorInclusion>> hitList = searchResponse.hits().hits();
                    List<InvestorInclusion> list = new ArrayList<>();
                    for (Hit<InvestorInclusion> mapHit : hitList) {
                        list.add(mapHit.source());
                    }
                    for(InvestorInclusion  i : list){
                        JointInvestment jointInvestment=new JointInvestment();

                        jointInvestment.setId(i.getId());
                        jointInvestment.setName(i.getName());
                        jointInvestment.setUrl(i.getLogoUrl());

                        Map<String, Long> countByProperty = i.getInvestDetailsList().stream()
                                .collect(Collectors.groupingBy(InvestDetails::getProjectName, Collectors.counting()));
                        int  count=Math.toIntExact(countByProperty.get(projectName));

                        jointInvestment.setCount((projectNameCount>count?count:projectNameCount));
                        resList.add(jointInvestment);
                    }
                } catch (Exception e) {
                    throw new Exception("【查询 -> 失败】从es中组合查询出错，错误信息为：{}");
                }
            }


        }
        return resList ;
    }



    /**
     * 查询投资机构收录列表
     *
     * @param investorInclusion 投资机构收录
     * @return 投资机构收录
     */
    @Override
    public List<InvestorInclusion> selectInvestorInclusionList(InvestorInclusion investorInclusion)
    {
        List<InvestorInclusion> resList=investorInclusionMapper.selectInvestorInclusionList(investorInclusion);
        for(InvestorInclusion p:resList){
            String   exStatus= inclusionExamineService.getExamineStatus(p.getId());
            if(exStatus!=null){
                p.setExStatus(exStatus);
            }else{
                p.setExStatus("");
            }
        }

        return resList;
    }

    @Override
    public TableDataInfo selectInvestorInclusionEsList(InvestorInclusion investorInclusion) throws Exception {
        TableDataInfo rspData = new TableDataInfo();
        // 将多个查询条件放入list中.
        List<Query> queries = new ArrayList<>();
        List<Query> locationQuery  = new ArrayList<>();
        List<Query> establishTimeQuery = new ArrayList<>();
        List<Query> querie = new ArrayList<>();
        List<Query> nameQuery = new ArrayList<>();
        //最新 最热
        String type = "";
        if (investorInclusion.getType().equals("0")) {
            //最新
            type = "createTime.keyword";
        } else {
            type = "likeCount.keyword";
        }
        // 升序降序
        String esSort = "";

        if (investorInclusion.getSort().equals("0")) {
            //最新
            esSort = "Desc";
        } else {
            esSort = "Asc";
        }

        //判断中英文  0英文  1中文
        Query byLang = TermQuery.of(a -> a
                .field("lang")
                .value(investorInclusion.getLang())
        )._toQuery();

        querie.add(byLang);

        //时间范围   单选
        if(investorInclusion.getTimeFrame()!=null){
            LocalDate now = LocalDate.now();

            //0近一个月 1近6个月2近1年 3今年至今
            if(investorInclusion.getTimeFrame().equals(0)){
                LocalDate oneMonthsAgo = now.minusMonths(1);
                Query time = RangeQuery.of(a -> a
                        .field("investDetailsList.createTime")
                        .from(oneMonthsAgo.format(DateTimeFormatter.ISO_DATE))
                        .to(now.format(DateTimeFormatter.ISO_DATE))
                )._toQuery();
                querie.add(time);
            }else if(investorInclusion.getTimeFrame().equals(1)){
                LocalDate sixMonthsAgo = now.minusMonths(6);
                Query time = RangeQuery.of(a -> a
                        .field("investDetailsList.createTime")
                        .from(sixMonthsAgo.format(DateTimeFormatter.ISO_DATE))
                        .to(now.format(DateTimeFormatter.ISO_DATE))
                )._toQuery();
                querie.add(time);
            }else if(investorInclusion.getTimeFrame().equals(1)){
                LocalDate startOfYear = LocalDate.of(now.getYear(), 1, 1);
                Query time = RangeQuery.of(a -> a
                        .field("investDetailsList.createTime")
                        .from(startOfYear.format(DateTimeFormatter.ISO_DATE))
                        .to(now.format(DateTimeFormatter.ISO_DATE))
                )._toQuery();
                querie.add(time);
            }
        }


        //成立时间   多选
        if (investorInclusion.getEstablishTime() != null) {
            // 将字符串转换成集合
            List<String> aList = Arrays.asList(investorInclusion.getEstablishTime().split(","));
            for (String establishTime : aList) {
                Query establishTimes = MatchQuery.of(m -> m
                        .query(establishTime)
                        .field("establishTime")
                        .fuzziness("AUTO")
                )._toQuery();
                establishTimeQuery.add(establishTimes);
            }
            Query bool =  BoolQuery.of(m -> m
                    .should(establishTimeQuery)
            )._toQuery();
            querie.add(bool);
        }

        //标签  类型
        if (investorInclusion.getLabel() != null) {
            // 将字符串转换成集合
            List<String> aList = Arrays.asList(investorInclusion.getLabel().split(","));
            for (String label : aList) {
                Query labels = MatchQuery.of(m -> m
                        .query(label)
                        .field("label")
                        .fuzziness("AUTO")
                )._toQuery();
                queries.add(labels);
            }
            Query bool1 =  BoolQuery.of(m -> m
                    .should(queries)
            )._toQuery();
            querie.add(bool1);
        }

        //地区
        if (investorInclusion.getLocation() != null) {
            // 将字符串转换成集合
            List<String> cList = Arrays.asList(investorInclusion.getLocation().split(","));
            for (String location : cList) {
                Query locations = MatchQuery.of(m -> m
                        .query(location)
                        .field("location")
                        .fuzziness("AUTO")
                )._toQuery();
                locationQuery.add(locations);
            }

            Query bool2 =  BoolQuery.of(m -> m
                    .should(locationQuery)
            )._toQuery();
            querie.add(bool2);

        }
        //投资机构名称
        if (investorInclusion.getName() != null) {
            // 将字符串转换成集合

                Query names = MatchQuery.of(m -> m
                        .query(investorInclusion.getName())
                        .field("name")
                        .fuzziness("AUTO")
                )._toQuery();
            nameQuery.add(names);
            Query bool2 =  BoolQuery.of(m -> m
                    .must(nameQuery)
            )._toQuery();
            querie.add(bool2);
        }


        try {
            // 从es中根据条件查询结果.
            String finalType = type;
            String finalEsSort = esSort;
            SearchResponse<InvestorInclusion> searchResponse = client.search(s -> s
                            .index("investor_inclusion")
                            .query(q -> q
                                    .bool(t -> t
                                            .must(querie)
                                    ))
                            .from((investorInclusion.getPageNum() - 1) * investorInclusion.getPageSize())
                            .size(investorInclusion.getPageSize())
                            .sort(sort -> sort.field(f -> f.field(finalType).order(SortOrder.valueOf(finalEsSort))))
                    , InvestorInclusion.class);
            List<Hit<InvestorInclusion>> hitList = searchResponse.hits().hits();

            List<InvestorInclusion> list = new ArrayList<>();
            for (Hit<InvestorInclusion> mapHit : hitList) {
                list.add(mapHit.source());
            }

            long total = searchResponse.hits().total() != null ? searchResponse.hits().total().value() : 0;

            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(list);
            rspData.setTotal(total);

            return rspData;
        } catch (Exception e) {
            throw new Exception("【查询 -> 失败】从es中组合查询出错，错误信息为：{}");

        }finally {
            if(rspData.getRows()==null){
                List<InvestorInclusion> list = new ArrayList<>();
                rspData.setRows(list);
                rspData.setTotal(0);
                rspData.setCode(HttpStatus.SUCCESS);
                rspData.setMsg("查询成功");
            }
            return rspData;
        }
    }

    @Override
    public InvestmentSurvey getInvestmentSurvey(String id, String lang) throws Exception {

        InvestmentSurvey  investmentSurvey=new InvestmentSurvey();
//       //获取组合投资数
//        List<JointInvestment>   resList= selectListCount(id, lang);
//        List<JointInvestment> result = resList.stream()
//                // 表示id为key， 接着如果有重复的，那么从对象o1与o2中筛选出一个，这里选择o1，
//                // 并把id重复，需要将nums和sums与o1进行合并的o2, 赋值给o1，最后返回o1
//                .collect(Collectors.toMap(JointInvestment::getId, a -> a, (o1,o2)-> {
//                    o1.setCount(o1.getCount() + o2.getCount());
//                    return o1;
//                })).values().stream().collect(Collectors.toList());
//        // 使用 Stream API 对集合中的对象属性求和
//        int sum = result.stream()
//                .mapToInt(JointInvestment::getCount)  // 假设对象中的属性叫做 value
//                .sum();
//        investmentSurvey.setComposeCount(sum);
//
//        //获取该收录
//        InvestorInclusion investorInclusion= selectEsInvestorInclusionById(id);
//        //获取投资的项目
//        List<InvestDetails> investDetailsList =new ArrayList<>();
//        if(investorInclusion.getInvestDetailsList()!=null){
//           investDetailsList=investorInclusion.getInvestDetailsList();
//            //获取历史投资数量
//            investmentSurvey.setCount(investDetailsList.size());
//            //获取近一年投资数量
//
//
//            long oneYearAgoTimestamp = System.currentTimeMillis() - (365L * 24 * 60 * 60 * 1000); // 计算一年前的时间戳
//
//            List<InvestDetails> filteredData = investDetailsList.stream()
//                    .filter(obj -> obj.getTime().after(new Date(oneYearAgoTimestamp))) // 过滤出日期在一年内的数据对象
//                    .collect(Collectors.toList());
//            investmentSurvey.setYearCount(filteredData.size());
//        }else{
//            investmentSurvey.setCount(0);
//            investmentSurvey.setYearCount(0);
//        }
//        //获取领投数量 得去项目收录查找
//        List<Query> querie = new ArrayList<>();
//
//
//        //判断中英文  0英文  1中文
//        Query byLang = TermQuery.of(a -> a
//                .field("lang")
//                .value(lang)
//        )._toQuery();
//
//        querie.add(byLang);
//
//        //查询投资机构
//         Query ecologys = TermQuery.of(m -> m
//                    .field("projectInvestDetailsList.investor")
//                    .value(investorInclusion.getName())
//            )._toQuery();
//            querie.add(ecologys);
//            // 从es中根据条件查询结果.
//            SearchResponse<ProjectInclusion> searchResponse = client.search(s -> s
//                            .index("project_inclusion")
//                            .query(q -> q
//                                    .bool(t -> t
//                                            .must(querie)
//                                    )
//                            )
//                    , ProjectInclusion.class);
//            List<Hit<ProjectInclusion>> hitList = searchResponse.hits().hits();
//
//            List<ProjectInclusion> list = new ArrayList<>();
//            for (Hit<ProjectInclusion> mapHit : hitList) {
//                list.add(mapHit.source());
//            }
//            //获取项目中该投资机构是领投的数量
//            long sumNumber=0L;
//             for(ProjectInclusion  pro: list){
//                 //获取
//               List<ProjectInvestDetails> projectInvestDetailsList=pro.getProjectInvestDetailsList();
//                 long count = projectInvestDetailsList.stream()
//                         .filter(obj -> obj.getInvestor().equals(investorInclusion.getName()) && obj.getLed().equals("0"))
//                         .count();
//                 sumNumber=+count;
//             }
//           investmentSurvey.setCount((int) sumNumber);

        return investmentSurvey;
    }


    @Override
    public InvestorInclusion selectInvestorInclusionByMainId(String mainId, String lang) {
        InvestorInclusion investorInclusion =new InvestorInclusion();
        investorInclusion.setMainId(mainId);
        investorInclusion.setLang(lang);
        return investorInclusionMapper.selectInvestorInclusionByMainId(investorInclusion);
    }

    /**
     * 新增投资机构收录
     *
     * @param investorInclusion 投资机构收录
     * @return 结果
     */
    @Override
    public String insertInvestorInclusion(InvestorInclusion investorInclusion)
    {
//        investorInclusion.setCreateTime(DateUtils.getNowDate());
//
//        //判断存草稿箱还是提交收录
//        //存草稿箱
//
//        //判断是否有主表id
//        if (investorInclusion.getMainId() == null) {
//
//            String uuid = IdUtils.simpleUUID();
//            String mainId = IdUtils.simpleUUID();
//            investorInclusion.setId(uuid);
//            investorInclusion.setMainId(mainId);
//            investorInclusion.setCreateTime(DateUtils.getNowDate());
//            investorInclusion.setCreateBy((String) StpUtil.getLoginId());
//
//            //新增社交媒体链接
//            List<SocialMediaConnection> smcList=new ArrayList<>();
//            if (investorInclusion.getSmcList() != null) {
//
//                for (SocialMediaConnection s : investorInclusion.getSmcList()) {
//                    s.setId(IdUtils.simpleUUID());
//                    //收录id
//                    s.setInclusionId(uuid);
//                    s.setCreateBy((String)StpUtil.getLoginId());
//                    s.setCreateTime(DateUtils.getNowDate());
//                    smcList.add(s);
//                    socialMediaConnectionMapper.insertSocialMediaConnection(s);
//                }
//            }
//            investorInclusion.setSmcList(smcList);
//            //关键事件
//            List<KeyEvent> eventList=new ArrayList<>();
//            if (investorInclusion.getEventList() != null) {
//                for (KeyEvent w : investorInclusion.getEventList()) {
//                    w.setId(IdUtils.simpleUUID());
//                    w.setInclusionId(uuid);
//                    w.setCreateBy((String)StpUtil.getLoginId());
//                    w.setCreateTime(DateUtils.getNowDate());
//                    eventList.add(w);
//                    keyEventMapper.insertKeyEvent(w);
//                }
//            }
//            investorInclusion.setEventList(eventList);
//            //投资详情
//            List<InvestDetails> investDetailsList =new ArrayList<>();
//            if (investorInclusion.getInvestDetailsList() != null) {
//                for (InvestDetails i : investorInclusion.getInvestDetailsList()) {
//
//                    i.setId(IdUtils.simpleUUID());
//                    //收录id
//                    i.setInclusionId(uuid);
//                    i.setCreateBy((String)StpUtil.getLoginId());
//                    i.setCreateTime(DateUtils.getNowDate());
//                    investDetailsList.add(i);
//                    investDetailsMapper.insertInvestDetails(i);
//                }
//            }
//            investorInclusion.setInvestDetailsList(investDetailsList);
//            //新增投资机构收录
//            investorInclusionMapper.insertInvestorInclusion(investorInclusion);
//            //新增投资机构收录主表
//            InvestorInclusionMain investorInclusionMain = new InvestorInclusionMain();
//            investorInclusionMain.setId(mainId);
//            investorInclusionMain.setCreateTime(DateUtils.getNowDate());
//            investorInclusionMain.setCreateBy((String)StpUtil.getLoginId());
//            investorInclusionMainMapper.insertInvestorInclusionMain(investorInclusionMain);
//
//
//            if (investorInclusion.getSubmitType().equals("0")) {
//
//                DraftBox draftBox = new DraftBox();
//                draftBox.setId(IdUtils.simpleUUID());
//                //人物名称
//                draftBox.setName(investorInclusion.getName());
//                //类型  投资机构
//                draftBox.setType("1");
//                draftBox.setProjectId(uuid);
//                draftBox.setUserId((String)StpUtil.getLoginId());
//                draftBox.setCreateBy((String)StpUtil.getLoginId());
//                draftBox.setCreateTime(DateUtils.getNowDate());
//                draftBox.setLang(investorInclusion.getLang());
//                draftBoxMapper.insertDraftBox(draftBox);
//            } else {
//
//                InclusionExamine inclusionExamine = new InclusionExamine();
//
//                inclusionExamine.setId(IdUtils.simpleUUID());
//                //未审核
//                inclusionExamine.setStatus("0");
//                inclusionExamine.setName(investorInclusion.getName());
//                //类型 投资机构
//                inclusionExamine.setType("1");
//                inclusionExamine.setProjectId(uuid);
//                inclusionExamine.setUserId((String)StpUtil.getLoginId());
//                inclusionExamine.setCreateBy((String)StpUtil.getLoginId());
//                inclusionExamine.setCreateTime(DateUtils.getNowDate());
//                inclusionExamine.setLang(investorInclusion.getLang());
//
//                //上传ipfs
//                JSONObject jsonObject = JSONObject.fromObject(investorInclusion);
//                byte[] jsonData = jsonObject.toString().getBytes();
//                try {
//                    String qmHash= ipfsService.uploadToIpfs(jsonData);
//                    inclusionExamine.setQmHash(qmHash);
//                } catch (IOException e) {
//                    throw new RuntimeException("上传ipfs错误");
//                }
//                inclusionExamineMapper.insertInclusionExamine(inclusionExamine);
//            }
//
//
//        } else {
//            String uuid = IdUtils.simpleUUID();
//            investorInclusion.setId(uuid);
//            investorInclusion.setCreateTime(DateUtils.getNowDate());
//            investorInclusion.setCreateBy((String)StpUtil.getLoginId());
//
//            //新增投资机构
//            investorInclusionMapper.insertInvestorInclusion(investorInclusion);
//            //新增社交媒体链接
//            List<SocialMediaConnection> smcList=new ArrayList<>();
//            if (investorInclusion.getSmcList() != null) {
//
//                for (SocialMediaConnection s : investorInclusion.getSmcList()) {
//                    s.setId(IdUtils.simpleUUID());
//                    //收录id
//                    s.setInclusionId(uuid);
//                    s.setCreateBy((String)StpUtil.getLoginId());
//                    s.setCreateTime(DateUtils.getNowDate());
//                    smcList.add(s);
//                    socialMediaConnectionMapper.insertSocialMediaConnection(s);
//                }
//            }
//            investorInclusion.setSmcList(smcList);
//            //关键事件
//            List<KeyEvent> eventList=new ArrayList<>();
//            if (investorInclusion.getEventList() != null) {
//                for (KeyEvent w : investorInclusion.getEventList()) {
//                    w.setId(IdUtils.simpleUUID());
//                    w.setInclusionId(uuid);
//                    w.setCreateBy((String)StpUtil.getLoginId());
//                    w.setCreateTime(DateUtils.getNowDate());
//                    eventList.add(w);
//                    keyEventMapper.insertKeyEvent(w);
//                }
//            }
//            investorInclusion.setEventList(eventList);
//            //投资详情
//            List<InvestDetails> investDetailsList =new ArrayList<>();
//            if (investorInclusion.getInvestDetailsList() != null) {
//                for (InvestDetails i : investorInclusion.getInvestDetailsList()) {
//
//                    i.setId(IdUtils.simpleUUID());
//                    //收录id
//                    i.setInclusionId(uuid);
//                    i.setCreateBy((String)StpUtil.getLoginId());
//                    i.setCreateTime(DateUtils.getNowDate());
//                    investDetailsList.add(i);
//                    investDetailsMapper.insertInvestDetails(i);
//                }
//            }
//
//            if (investorInclusion.getSubmitType().equals("0")) {
//
//                DraftBox draftBox = new DraftBox();
//                draftBox.setId(IdUtils.simpleUUID());
//                //kol昵称
//                draftBox.setName(investorInclusion.getName());
//                //类型  投资机构
//                draftBox.setType("1");
//                draftBox.setProjectId(uuid);
//                draftBox.setUserId((String)StpUtil.getLoginId());
//                draftBox.setCreateBy((String)StpUtil.getLoginId());
//                draftBox.setCreateTime(DateUtils.getNowDate());
//                draftBox.setLang(investorInclusion.getLang());
//                draftBoxMapper.insertDraftBox(draftBox);
//            } else {
//
//                InclusionExamine inclusionExamine = new InclusionExamine();
//
//                inclusionExamine.setId(IdUtils.simpleUUID());
//                //未审核
//                inclusionExamine.setStatus("0");
//                inclusionExamine.setName(investorInclusion.getName());
//                //类型 投资机构
//                inclusionExamine.setType("1");
//                inclusionExamine.setProjectId(uuid);
//                inclusionExamine.setUserId((String)StpUtil.getLoginId());
//                inclusionExamine.setCreateBy((String)StpUtil.getLoginId());
//                inclusionExamine.setCreateTime(DateUtils.getNowDate());
//                inclusionExamine.setLang(investorInclusion.getLang());
//                //上传ipfs
//                JSONObject jsonObject = JSONObject.fromObject(investorInclusion);
//                byte[] jsonData = jsonObject.toString().getBytes();
//                try {
//                    String qmHash= ipfsService.uploadToIpfs(jsonData);
//                    inclusionExamine.setQmHash(qmHash);
//                } catch (IOException e) {
//                    throw new RuntimeException("上传ipfs错误");
//                }
//                inclusionExamineMapper.insertInclusionExamine(inclusionExamine);
//
//            }

//        }
        return investorInclusion.getMainId();
    }

    @Override
    public String insertNewInvestorInclusion(InvestorInclusion investorInclusion)
    {
//        //先判断是否有人已经提交审核 能否继续更新
//        InvestorInclusion newInvestorInclusion=new InvestorInclusion();
//        newInvestorInclusion.setMainId(investorInclusion.getMainId());
//        List<InvestorInclusion>  resList=  investorInclusionMapper.selectInvestorInclusionList(newInvestorInclusion);
//        for(int a=0;a<resList.size();a++){
//            InclusionExamine inclusionExamine =new InclusionExamine();
//            inclusionExamine.setProjectId(resList.get(a).getId());
//            //待审核
//            inclusionExamine.setStatus("0");
//            List<InclusionExamine>  inclusionList=  inclusionExamineService.selectInclusionExamineList(inclusionExamine);
//
//            if(inclusionList.size()>0){
//                return  "该收录存在待审核状态，无法更新";
//            }
//        }
//
//
//            String uuid = IdUtils.simpleUUID();
//            investorInclusion.setId(uuid);
//            investorInclusion.setUpdateTime(DateUtils.getNowDate());
//            investorInclusion.setUpdateBy((String)StpUtil.getLoginId());
//
//            //新增投资机构
//            investorInclusionMapper.insertInvestorInclusion(investorInclusion);
//        //新增社交媒体链接
//        List<SocialMediaConnection> smcList=new ArrayList<>();
//        if (investorInclusion.getSmcList() != null) {
//
//            for (SocialMediaConnection s : investorInclusion.getSmcList()) {
//                s.setId(IdUtils.simpleUUID());
//                //收录id
//                s.setInclusionId(uuid);
//                s.setCreateBy((String)StpUtil.getLoginId());
//                s.setCreateTime(DateUtils.getNowDate());
//                smcList.add(s);
//                socialMediaConnectionMapper.insertSocialMediaConnection(s);
//            }
//        }
//        investorInclusion.setSmcList(smcList);
//        //关键事件
//        List<KeyEvent> eventList=new ArrayList<>();
//        if (investorInclusion.getEventList() != null) {
//            for (KeyEvent w : investorInclusion.getEventList()) {
//                w.setId(IdUtils.simpleUUID());
//                w.setInclusionId(uuid);
//                w.setCreateBy((String)StpUtil.getLoginId());
//                w.setCreateTime(DateUtils.getNowDate());
//                eventList.add(w);
//                keyEventMapper.insertKeyEvent(w);
//            }
//        }
//        investorInclusion.setEventList(eventList);
//        //投资详情
//        List<InvestDetails> investDetailsList =new ArrayList<>();
//        if (investorInclusion.getInvestDetailsList() != null) {
//            for (InvestDetails i : investorInclusion.getInvestDetailsList()) {
//
//                i.setId(IdUtils.simpleUUID());
//                //收录id
//                i.setInclusionId(uuid);
//                i.setCreateBy((String)StpUtil.getLoginId());
//                i.setCreateTime(DateUtils.getNowDate());
//                investDetailsList.add(i);
//                investDetailsMapper.insertInvestDetails(i);
//            }
//        }
//        investorInclusion.setInvestDetailsList(investDetailsList);
//
//            if (investorInclusion.getSubmitType().equals("0")) {
//
//                DraftBox draftBox = new DraftBox();
//                draftBox.setId(IdUtils.simpleUUID());
//                //kol昵称
//                draftBox.setName(investorInclusion.getName());
//                //类型  投资机构
//                draftBox.setType("1");
//                draftBox.setProjectId(uuid);
//                draftBox.setUserId((String)StpUtil.getLoginId());
//                draftBox.setUpdateBy((String)StpUtil.getLoginId());
//                draftBox.setUpdateTime(DateUtils.getNowDate());
//                draftBox.setLang(investorInclusion.getLang());
//                draftBoxMapper.insertDraftBox(draftBox);
//            } else {
//
//                InclusionExamine inclusionExamine = new InclusionExamine();
//
//                inclusionExamine.setId(IdUtils.simpleUUID());
//                //未审核
//                inclusionExamine.setStatus("0");
//                inclusionExamine.setName(investorInclusion.getName());
//                //类型 投资机构
//                inclusionExamine.setType("1");
//                inclusionExamine.setProjectId(uuid);
//                inclusionExamine.setUserId((String)StpUtil.getLoginId());
//                inclusionExamine.setUpdateBy((String)StpUtil.getLoginId());
//                inclusionExamine.setUpdateTime(DateUtils.getNowDate());
//                inclusionExamine.setLang(investorInclusion.getLang());
//                //上传ipfs
//                JSONObject jsonObject = JSONObject.fromObject(investorInclusion);
//                byte[] jsonData = jsonObject.toString().getBytes();
//                try {
//                    String qmHash= ipfsService.uploadToIpfs(jsonData);
//                    inclusionExamine.setQmHash(qmHash);
//                } catch (IOException e) {
//                    throw new RuntimeException("上传ipfs错误");
//                }
//                inclusionExamineMapper.insertInclusionExamine(inclusionExamine);

//            }
        return investorInclusion.getMainId();
    }

    /**
     * 修改投资机构收录
     *
     * @param investorInclusion 投资机构收录
     * @return 结果
     */
    @Override
    public int updateInvestorInclusion(InvestorInclusion investorInclusion)
    {
        investorInclusion.setUpdateTime(DateUtils.getNowDate());
//        investorInclusion.setUpdateBy((String)StpUtil.getLoginId());
//        //新增社交媒体链接
//        if (investorInclusion.getSmcList() != null) {
//            for (SocialMediaConnection s : investorInclusion.getSmcList()) {
//                s.setUpdateBy((String)StpUtil.getLoginId());
//                s.setUpdateTime(DateUtils.getNowDate());
//                socialMediaConnectionMapper.updateSocialMediaConnection(s);
//            }
//        }
//        //关键事件
//        if (investorInclusion.getEventList() != null) {
//
//            for (KeyEvent w : investorInclusion.getEventList()) {
//                w.setUpdateBy((String)StpUtil.getLoginId());
//                w.setUpdateTime(DateUtils.getNowDate());
//                keyEventMapper.updateKeyEvent(w);
//            }
//        }
//        //投资详情
//        if (investorInclusion.getInvestDetailsList() != null) {
//            for (InvestDetails i : investorInclusion.getInvestDetailsList()) {
//                i.setUpdateBy((String)StpUtil.getLoginId());
//                i.setUpdateTime(DateUtils.getNowDate());
//                investDetailsMapper.updateInvestDetails(i);
//            }
//        }
//
//        //判断存草稿箱 0还是提交收录 1
//        if (investorInclusion.getSubmitType().equals("0")) {
//            //通过项目id 查询当前草稿箱内的是否有这条数据
//            DraftBox  draftBox= draftBoxMapper.selectDraftBoxByProId(investorInclusion.getId());
//                draftBox.setName(investorInclusion.getName());
//                draftBox.setUpdateBy((String)StpUtil.getLoginId());
//                draftBox.setUpdateTime(DateUtils.getNowDate());
//                draftBox.setLang(investorInclusion.getLang());
//                draftBoxMapper.updateDraftBox(draftBox);
//
//        }

        return investorInclusionMapper.updateInvestorInclusion(investorInclusion);
    }

    /**
     * 批量删除投资机构收录
     *
     * @param ids 需要删除的投资机构收录主键
     * @return 结果
     */
    @Override
    public int deleteInvestorInclusionByIds(String[] ids)
    {
        return investorInclusionMapper.deleteInvestorInclusionByIds(ids);
    }

    /**
     * 删除投资机构收录信息
     *
     * @param id 投资机构收录主键
     * @return 结果
     */
    @Override
    public int deleteInvestorInclusionById(String id)
    {
        return investorInclusionMapper.deleteInvestorInclusionById(id);
    }
}
